<template>
  <div class="yf-filter p-10">
    <el-row class="p-10">
      <el-col :span="1" class="title">{{title}}:</el-col>
      <el-col :span="22" class="pl-20 list">
        <span @click="toggleAll()" :class="{active:isSelectAll()}">全部</span>
        <span v-for="item in list" @click="selectOne(item)" :class="{active:isSelect(item)}">{{item[label]}}</span>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  name: 'YfFilter',
  props: {
    title: {
      type: String
    },
    name: {
      type: String
    },
    label: {
      type: String,
      default: 'label'
    },
    resultKey: {
      type: String,
      default: 'value'
    },
    list: {
      type: Array,
      default: []
    },
    result: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      selectList: []
    }
  },
  methods: {
    updateResult(list) {
      this.result[this.name] = []
      this.selectList.forEach((v) => {
        this.result[this.name].push(v[this.resultKey])
      })
    },
    isSelectAll() {
      return this.selectList.length !== 0 && this.selectList.length === this.list.length
    },
    isSelect(item) {
      return this.selectList.some((v) => v[this.label] === item[this.label])
    },
    selectAll() {
      this.selectList = this.list.concat()
    },
    toggleAll() {
      if (this.isSelectAll()) {
        this.selectList = []
      } else {
        this.selectAll()
      }
      this.updateResult(this.selectList)
    },
    selectOne(item) {
      if (this.isSelect(item)) {
        this.selectList = this.selectList.filter((v) => v[this.label] !== item[this.label])
      } else {
        this.selectList.push(item)
      }
      this.updateResult(this.selectList)
    }
  }
}

</script>
<style rel="stylesheet/scss" lang="scss">
@import '../../styles/mixin.scss';
@import '../../styles/variables.scss';
.yf-filter {
  .title {
    text-align: right;
  }
  .list {
    span {
      margin-right: 10px;
      padding: 5px 10px;
      border-radius: 5px;
      cursor: pointer;
      &:hover,&.active{
        background-color: $blue;
        color: #fff;
      }
    }
  }
}
</style>
